﻿using FluentValidation.Results;
using System;
using System.Collections.Generic;
using System.Linq;
using XUCore.Extensions;

namespace XUCore.Ddd.Domain
{
    public static class Failure
    {
        public static void Error(List<ValidationFailure> failures)
        {
            throw new ValidationException(failures);
        }
        /// <summary>
        /// 抛出异常
        /// </summary>
        /// <typeparam name="TEnum"></typeparam>
        /// <param name="subCode">subcode枚举类</param>
        /// <param name="error">错误信息</param>
        /// <exception cref="ValidationException"></exception>
        public static void Error<TEnum>(TEnum subCode, string error = "") where TEnum : struct
        {
            throw new ValidationException(new List<ValidationFailure> { new ValidationFailure(subCode.ToString(), error) });
        }
        /// <summary>
        /// 抛出异常
        /// </summary>
        /// <param name="propertyName">属性名，字段名</param>
        /// <param name="error">错误信息</param>
        /// <exception cref="ValidationException"></exception>
        public static void Error(string propertyName, string error)
        {
            throw new ValidationException(new List<ValidationFailure> { new ValidationFailure(propertyName, error) });
        }
        /// <summary>
        /// 抛出异常
        /// </summary>
        /// <param name="error">错误信息</param>
        public static void Error(string error) => Error("", error);
        /// <summary>
        /// 是否为ValidationException
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static bool IsFailure(this Exception ex)
        {
            return ex is ValidationException;
        }

        public static bool ThrowValidation(this ValidationResult validationResult)
        {
            if (!validationResult.IsValid)
                Error(validationResult.Errors);

            return true;
        }
        /// <summary>
        /// 获取错误信息
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="separator"></param>
        /// <param name="field"></param>
        /// <returns></returns>
        public static string GetErrors(this ValidationException ex, string separator = "", string field = "")
        {
            return ex.Failures.Select(c => c.Value.Join(separator)).Join(field);
        }
    }
}
